<?php

namespace App\Http\Controllers;

use App\Models\Brand;
use App\Models\Industry;
use App\Models\Template;
use Illuminate\Http\Request;

class TemplateController extends Controller {

    public function index(Request $request) {
        $input = $request->all();
        if(!isset($input['brand']) OR !isset($input['batch']) OR !isset($input['price'])) {
            return json_encode('品牌、价格、批次都不能为空',320);
        }
        $b = Brand::where('name', $input['brand'])->first();
        if(is_null($b) or is_null($b->industry_id)) {
            return json_encode('该品牌资料不全，无法获取模板',320);
        }
        $template = Template::select('time', 'invalid', 'name', 'content');
        if(!is_null($input['batch'])) {
            $template = $template->where('batch', $input['batch']);
        }
        $template = $template->where('invalid', false)
                ->where('industry_id', $b->industry_id)
                ->inRandomOrder()->first();
        $data = [];
        $data['name'] = $this->formatContent($template->name, $input['brand'], $input['price']);
        $data['content'] = $this->formatContent($template->content, $input['brand'], $input['price']);
        $template->time = $template->time + 1;
        if($template->time >= 5) {
            $template->invalid = true;
        }
        $template->save();
        return json_encode($data,320);
    }
    
    private function formatContent($content, $name, $price) {
        $nameFormat = str_replace("{name}", $name, $content);
        $priceFormat = str_replace("{price}", $price, $nameFormat);
        return $priceFormat;
    }
}
